package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Resource
    CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {
        //解决缓存穿透
        Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY, id, Shop.class
                , this::getById, RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
//        queryWithPassThrough(id);
        //用互斥锁解决缓存击穿
//        Shop shop = queryWithMutex(id);
        if (shop == null) {
            return Result.fail("店铺不存在！");
        }
        return Result.ok(shop);
    }


    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    //利用逻辑时间过期，解决缓存击穿问题
    public Shop queryWithLogicalExpire(Long id) {
        String cacheKey = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(cacheKey);
        //未命中redis直接返回null
        if (StrUtil.isBlank(shopJson)) {
            return null;
        }
        //命中先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断缓存是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期直接返回
            return shop;
        }
        //过期了直接进行缓存重建
        //获取互斥锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        Boolean aBoolean = this.tryLock(lockKey);
        //判断是否获取锁成功
        if (aBoolean) {
            //获取成功，开启线程，执行重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                saveShop2Redis(id, 20L);
                unlock(lockKey);
            });
        }
        return shop;
    }

    //利用互斥锁解决缓存击穿问题
    public Shop queryWithMutex(Long id) {
        String cacheKey = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(cacheKey);

        if (StrUtil.isNotBlank(shopJson)) {
            log.debug("从缓存获取店铺数据，店铺ID: {}");  // 缓存命中
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        if (shopJson.equals("")) {
            return null;
        }
        //实现缓存重建
        //获取互斥锁
        String keyLock = RedisConstants.LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            Boolean aBoolean = tryLock(keyLock);
            //判断是否获取到互斥锁
            if (!aBoolean) {
                //失败，休眠并重试
                Thread.sleep(50);

                return queryWithMutex(id);
            }
            //成功根据id查询数据库
            shop = getById(id);
            //模拟重建延时
            Thread.sleep(200);
            //给redis返回一个null值，防止缓存穿透的
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(cacheKey, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //从数据库中查询到的数据写入缓存
            stringRedisTemplate.opsForValue().set(cacheKey, JSONUtil.toJsonStr(shop),
                    RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(keyLock);
        }
        return shop;
    }
    //返回空值，来解决缓存穿透
    public Shop queryWithPassThrough(Long id) {
        String cacheKey = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJson = stringRedisTemplate.opsForValue().get(cacheKey);

        if (StrUtil.isNotBlank(shopJson)) {
            log.debug("从缓存获取店铺数据，店铺ID: {}");  // 缓存命中
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        if (shopJson.equals("")) {
            return null;
        }

        log.debug("缓存未命中，从数据库查询店铺，店铺ID: {}");  // 缓存未命中
        Shop shop = getById(id);

        if (shop == null) {
            stringRedisTemplate.opsForValue().set(cacheKey, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        stringRedisTemplate.opsForValue().set(cacheKey, JSONUtil.toJsonStr(shop),
                RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return shop;
    }

    //获取锁(根据当前操作的类型和店铺id作为key，利用setnx唯一性)
    public Boolean tryLock(String key) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }
    //释放锁
    public void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    //缓存重建(逻辑过期时间)
    private void saveShop2Redis(Long id, Long expireSeconds) {
        //查询店铺数据
        Shop shop = getById(id);
        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    @Override
    @Transactional
    //通过事务来保证一致性
    public Result updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺不存在");
        }
        //先更新数据库
        updateById(shop);
        //再删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }
}
